package com.youxin.chat.user.mq.consumer.message;

import com.alibaba.fastjson.JSONObject;

import com.youxin.base.MsgDto;
import com.youxin.common.constant.MsgTypeEnum;
import com.youxin.chat.user.manager.ImManager;
import com.youxin.chat.user.mapper.UserInfoMapper;
import com.youxin.chat.user.model.UserInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class KickGroupMsgResolver implements MsgResolver {

    private Logger logger = LoggerFactory.getLogger(KickGroupMsgResolver.class);

    @Resource
    private ImManager imManager;

    @Resource
    private UserInfoMapper userInfoMapper;




    @Override
    public Boolean supportType(String type) {
        return MsgTypeEnum.KICK_GROUP.getType().equalsIgnoreCase(type);
    }

    @Override
    public void doResolve(MsgDto msgDto) {
        logger.info("处理移出群组通知，data={}", JSONObject.toJSONString(msgDto));
        try {
            JSONObject jsonObject = JSONObject.parseObject(msgDto.getData());
            String userNo = jsonObject.getString("applyUserNo");
            List<String> kickUserNos = jsonObject.getJSONArray("kickUserNo").toJavaList(String.class);
            String groupNo = jsonObject.getString("groupNo");
            Map<String, Object> dataMap = new HashMap<>();
            UserInfo userInfo = userInfoMapper.selectByUserNo(userNo);
            List<String> targetUserIds = new ArrayList<>();
            List<String> targetUserDisplayNames = new ArrayList<>();
            for(String item : kickUserNos) {
                UserInfo targetUserInfo =  userInfoMapper.selectByUserNo(item);
                targetUserIds.add(targetUserInfo.getUserNo());
                targetUserDisplayNames.add(Optional.ofNullable(targetUserInfo.getNickName()).orElse(""));
            }
            dataMap.put("operatorNickname", userInfo.getNickName());
            dataMap.put("targetUserIds", targetUserIds);
            dataMap.put("targetUserDisplayNames",targetUserDisplayNames);
            String msg = "移出群成员";
            imManager.sendGroupMsg("Kicked",imManager.getSystemNo(), Arrays.asList(groupNo), userNo, JSONObject.toJSONString(dataMap), msg);
            logger.info("处理移出群组通知完成，data={}", JSONObject.toJSONString(msgDto));

        } catch (Exception e) {
            logger.info("处理移出群组通知失败，error={}", e);

        }
    }
}
